package com.tts.service;

import com.tts.dto.LoginData;
import com.tts.dto.LoginRequest;
import com.tts.dto.LoginResponse;
import com.tts.dto.RegisterRequest;
import com.tts.entity.User;
import com.tts.exception.BusinessException;
import com.tts.repository.UserRepository;
import com.tts.util.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
import java.time.LocalDateTime;

@Service
@Slf4j
public class AuthService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private PasswordEncoder passwordEncoder;

    public LoginResponse login(LoginRequest request) {
        log.info("尝试登录用户: {}", request.getUsername());
        
        User user = userRepository.findByUsername(request.getUsername())
            .orElseThrow(() -> new BusinessException("用户不存在"));

        if (!passwordEncoder.matches(request.getPassword(), user.getPassword())) {
            log.error("密码错误: {}", request.getUsername());
            throw new BusinessException("密码错误");
        }

        log.info("用户 {} 登录成功", user.getUsername());

        String token = jwtTokenUtil.generateToken(user.getUsername(), user.getRole().name());

        return LoginResponse.builder()
            .code(200)
            .message("登录成功")
            .data(LoginData.builder()
                .token(token)
                .username(user.getUsername())
                .role(user.getRole())
                .build())
            .build();
    }

    public void register(RegisterRequest request) {
        if (userRepository.existsByUsername(request.getUsername())) {
            throw new BusinessException("用户名已存在");
        }

        User user = new User();
        user.setUsername(request.getUsername());
        user.setPassword(passwordEncoder.encode(request.getPassword()));
        user.setRole(User.UserRole.USER);
        user.setStatus(User.UserStatus.ENABLE);
        user.setCreatedTime(LocalDateTime.now());
        user.setUpdatedTime(LocalDateTime.now());

        userRepository.save(user);
        log.info("新用户注册成功: {}", request.getUsername());
    }
}